##########################################################################################################################################
###### This is the file containing further merger regression results
###############################
# It creates the final results for Table 6
# Please note that in some instances, the paper contains some formatting modifications
# such as a "log()" that is not automatically added here or that we present the negative
# of tsim, while most output here is generated for the positive

# This is just the final step. There are other code files that are used for data preparation
# This processed data are saved and loaded in this code

#######
# set to your working directory:
setwd("C:\\Users\\Admin\\OneDrive\\Desktop\\Market Power and Systematic Risk - Data and Code")
getwd()

###################################
load("Mergers_with_SIC_NEW.RData")

Mergers_New$YearMonth = as.numeric(paste0(format(Mergers_New$Date.Effective.or.Unconditional,"%Y"),format(Mergers_New$Date.Effective.or.Unconditional,"%m")))
Mergers_New$YearMonth_ann = as.numeric(paste0(format(Mergers_New$Date.Announced,"%Y"),format(Mergers_New$Date.Announced,"%m")))
Mergers_New = Mergers_New[Mergers_New$Date.Announced>="1989-01-01",]

Mergers_New = Mergers_New[Mergers_New$Deal.Status == "Completed",]

Mergers_New = Mergers_New[Mergers_New$Percentage.of.Shares.Held.at.Announcement<10 | is.na(Mergers_New$Percentage.of.Shares.Held.at.Announcement),]

#only obtain mergers where at least 50 % of the Stock was Aquired:
Mergers_New = Mergers_New[Mergers_New$Percentage.of.Shares.Acquired.in.Transaction > 50 | is.na(Mergers_New$Percentage.of.Shares.Acquired.in.Transaction), ]


#Specify the M.A.Type
Mergers_New = Mergers_New[Mergers_New$M.A.Type == "Disclosed Dollar Value Deal" | 
                            Mergers_New$M.A.Type == "Undisclosed Dollar Value Deal",]

Mergers_New = Mergers_New[Mergers_New$Acquiror.6.digit.CUSIP != Mergers_New$Target.6.digit.CUSIP & !is.na(Mergers_New$Acquiror.6.digit.CUSIP),]

################################ Specifications #########################################################

Mergers_New = Mergers_New[apply(sapply(c("Acquire competitors technology/strategic assets",
                                         "Strengthen existing operations/expand presence in primary market",
                                         "Strengthen operations", "Create synergies", "Concentrate on core businesses/assets"), 
                                       grepl, Mergers_New$Purpose),1,any),]
##########################################################

load("Control_Panel.RData")

Panel_New<-Panel_New[order(Panel_New$YearMonth),]
Panel_New$Weight_Beta_M_lag=Panel_New$Weight_Beta_M
require(plyr)
Panel_New <- ddply( 
  Panel_New, .(PERMNO), transform,
  Weight_Beta_M_lag = c( NA, Weight_Beta_M[-length(Weight_Beta_M)] ) 
)

Panel_New$six_digit_cusip = substr(Panel_New$cusip,1,6)

Mergers_New = Mergers_New[Mergers_New$Acquiror.6.digit.CUSIP%in%Panel_New$six_digit_cusip,]
Mergers_New$Year=floor(Mergers_New$YearMonth/100)
Mergers_New$Year=Mergers_New$Year+1
Mergers_New$Year2=Mergers_New$Year+1

Panel_New_all = merge(Panel_New,Mergers_New,by.x=c("year","six_digit_cusip"),by.y=c("Year","Acquiror.6.digit.CUSIP"),all.x=T)
Panel_New_all = merge(Panel_New_all,Mergers_New,by.x=c("year","six_digit_cusip"),by.y=c("Year2","Acquiror.6.digit.CUSIP"),all.x=T)

Panel_New_all$COMNAM = NULL
Panel_New_all$conm = NULL
Panel_New_all$tic = NULL
Panel_New_all$TICKER = NULL

Panel_New_all$Merger_Dummy = ifelse(is.na(Panel_New_all$Date.Effective.or.Unconditional.x)&is.na(Panel_New_all$Date.Effective.or.Unconditional.y),0,1)
sum(Panel_New_all$Merger_Dummy)
library(data.table)
setDT(Panel_New_all)
Panel_New_all = Panel_New_all[order(Panel_New_all$Time, decreasing = F),]


ExtAeND = function(x,days){
  #At this Point in Time a merger happened
  a = which(x==1)
  if(length(a)>1){
    #So this is 12 Months later, or the maximum of a series
    b = pmin(which(x==1) + days,length(x))
    #So create all of them Series:
    c = mapply(seq,a,b,SIMPLIFY = F)
    x[unique(unlist(c))] = 1
  }
  
  return(x)
}

setDF(Panel_New_all)
Temp = Panel_New_all[,c("Time","YearMonth.x","year","NAICS","PERMNO","Weight_Beta_M","HHI","prodmktfluid","tnic3hhi","tnic3tsimm","Age","Momentum","Illiquidity","MktCap","Mkt_Book","Default_Spread",
                        "Financial_Leverage", "Operating_Leverage","Firm_size","InvestmentRates","ROE","Logat","Dividend_Dummy","q","I_Vol","Merger_Dummy")]#


library(lfe)
for(i in 1:dim(Temp)[2]){
  Temp[,i][Temp[,i] == Inf] = NA
  Temp[,i][Temp[,i] == -Inf] = NA
}
Temp = na.omit(Temp)

source("Table_Functions.R")

#The Merger Analysis:
A_tsim2_multi = felm(tnic3tsimm ~ Merger_Dummy + scale(log(Age)) + scale(Logat) + scale(Default_Spread) + Dividend_Dummy + scale(Financial_Leverage) + scale(log(MktCap)) + scale(Illiquidity) + scale(InvestmentRates) + scale(I_Vol) +  
                       scale(log(Mkt_Book)) + scale(Momentum)  + scale(Operating_Leverage) +  scale(q)  + scale(ROE) | PERMNO | 0 | NAICS + year, data = Temp, cmethod="reghdfe")
A_tsim2_uni = felm(tnic3tsimm ~ Merger_Dummy  | PERMNO  | 0 | NAICS + year, data = Temp, cmethod="reghdfe")


###################################

Panel_New_all$Merger_Dummy = ifelse(is.na(Panel_New_all$Date.Effective.or.Unconditional.x),0,1)
sum(Panel_New_all$Merger_Dummy)
library(data.table)
setDT(Panel_New_all)
Panel_New_all = Panel_New_all[order(Panel_New_all$Time, decreasing = F),]


#Conduct the Panel Regressions:
setDF(Panel_New_all)

Temp = Panel_New_all[,c("Time","YearMonth.x","year","NAICS","PERMNO","Weight_Beta_M","HHI","prodmktfluid","tnic3hhi","tnic3tsimm","Age","Momentum","Illiquidity","MktCap","Mkt_Book","Default_Spread",
                        "Financial_Leverage", "Operating_Leverage","Firm_size","InvestmentRates","ROE","Logat","Dividend_Dummy","q","I_Vol","Merger_Dummy")]#

library(lfe)
for(i in 1:dim(Temp)[2]){
  Temp[,i][Temp[,i] == Inf] = NA
  Temp[,i][Temp[,i] == -Inf] = NA
}
Temp = na.omit(Temp)

#The Merger Analysis:
A_tsim1_multi = felm(tnic3tsimm ~ Merger_Dummy + scale(log(Age)) + scale(Logat) + scale(Default_Spread) + Dividend_Dummy + scale(Financial_Leverage) + scale(log(MktCap)) + scale(Illiquidity) + scale(InvestmentRates) + scale(I_Vol) +  
                       scale(log(Mkt_Book)) + scale(Momentum)  + scale(Operating_Leverage) +  scale(q)  + scale(ROE) | PERMNO | 0 | NAICS + year, data = Temp, cmethod="reghdfe")
A_tsim1_uni = felm(tnic3tsimm ~ Merger_Dummy  | PERMNO  | 0 | NAICS + year, data = Temp, cmethod="reghdfe")

# Output Table

#Bottom: R^2 and below t-stat:
Market_Paper = data.frame(Coeff_Names = rep(NA,2*length(coef(A_tsim1_multi))+2),ProdFluid = rep(NA,2*length(coef(A_tsim1_multi))+2), 
                          ProdFluidCom = rep(NA,2*length(coef(A_tsim1_multi))+2),HHI = rep(NA,2*length(coef(A_tsim1_multi))+2),HHICom = rep(NA,2*length(coef(A_tsim1_multi))+2))

Names = c("Merger_Dummy","log(Age)","log(AT)","Default~spread","Dividend","Financial~leverage","log(Firm~size)","Illiquidity","Investment~rate","iVol",
          "log(Mkt/Book)","Momentum","Operating~leverage","q","ROE")

Market_Paper$Coeff_Names[seq(from=1,to=(nrow(Market_Paper)-2),by=2)] = Names
Market_Paper$Coeff_Names[(nrow(Market_Paper)-1)] = "R^2"
Market_Paper$Coeff_Names[(nrow(Market_Paper))] = "Fixed-Effects"

Market_Paper$ProdFluid[c(1)] = paste0(as.character(Lag_zero(round(summary(A_tsim1_uni)$coefficients[,1],digits=3),digits=3)),star_function(summary(A_tsim1_uni)$coefficients[,4]))
Market_Paper$ProdFluid[c(2)] = paste0("(",Lag_zero(round(summary(A_tsim1_uni)$coefficients[,3],digits=3),digits=3),")")
Market_Paper$ProdFluid[nrow(Market_Paper)-1] = as.character(Lag_zero(round(summary(A_tsim1_uni)$r2adj,digits=4) * 100,digits=2))
Market_Paper$ProdFluid[nrow(Market_Paper)] = "Yes"

Market_Paper$ProdFluidCom[c(1,seq(from=3,to=(nrow(Market_Paper)-2),by=2))] = paste0(as.character(Lag_zero(round(summary(A_tsim1_multi)$coefficients[,1],digits=3),digits=3)),star_function(summary(A_tsim1_multi)$coefficients[,4]))
Market_Paper$ProdFluidCom[c(2,seq(from=4,to=(nrow(Market_Paper)-2),by=2))] = paste0("(",Lag_zero(round(summary(A_tsim1_multi)$coefficients[,3],digits=3),digits=3),")")
Market_Paper$ProdFluidCom[nrow(Market_Paper)-1] = as.character(Lag_zero(round(summary(A_tsim1_multi)$r2adj,digits=4) * 100,digits=2))
Market_Paper$ProdFluidCom[nrow(Market_Paper)] = "Yes"

Market_Paper$HHI[c(1)] = paste0(as.character(Lag_zero(round(summary(A_tsim2_uni)$coefficients[,1],digits=3),digits=3)),star_function(summary(A_tsim2_uni)$coefficients[,4]))
Market_Paper$HHI[c(2)] = paste0("(",Lag_zero(round(summary(A_tsim2_uni)$coefficients[,3],digits=3),digits=3),")")
Market_Paper$HHI[nrow(Market_Paper)-1] = as.character(Lag_zero(round(summary(A_tsim2_uni)$r2adj,digits=4) * 100,digits=2))
Market_Paper$HHI[nrow(Market_Paper)] = "Yes"



Market_Paper$HHICom[c(1,seq(from=3,to=(nrow(Market_Paper)-2),by=2))] = paste0(as.character(Lag_zero(round(summary(A_tsim2_multi)$coefficients[,1],digits=3),digits=3)),star_function(summary(A_tsim2_multi)$coefficients[,4]))
Market_Paper$HHICom[c(2,seq(from=4,to=(nrow(Market_Paper)-2),by=2))] = paste0("(",Lag_zero(round(summary(A_tsim2_multi)$coefficients[,3],digits=3),digits=3),")")
Market_Paper$HHICom[nrow(Market_Paper)-1] = as.character(Lag_zero(round(summary(A_tsim2_multi)$r2adj,digits=4) * 100,digits=2))
Market_Paper$HHICom[nrow(Market_Paper)] = "Yes"


library(xtable)
print(xtable(Market_Paper),include.rownames=F,sanitize.text.function=function(x){x})

